/*
 * @lc app=leetcode.cn id=543 lang=csharp
 *
 * [543] 二叉树的直径
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    Dictionary<TreeNode,int> depth = new();
    int max = 0;
    
    private void PostOrder(TreeNode root)
    {
        if (root == null)
        {
            return;   
        }
        
        PostOrder(root.left);
        PostOrder(root.right);
        
        var leftDepth = root.left != null ? depth.GetValueOrDefault(root.left) : 0;
        var rightDepth = root.right != null ? depth.GetValueOrDefault(root.right) : 0;
        depth[root] = Math.Max(leftDepth,rightDepth) + 1;
        max = Math.Max(max, depth[root]);
    }
    
    
    public int DiameterOfBinaryTree(TreeNode root) {
        PostOrder(root);
        return max;
    }
}
// @lc code=end

